package cn.cutie.clot.registry.cluster;

import cn.cutie.clot.registry.ClotRegistryConfigProperties;
import cn.cutie.clot.registry.service.ClotRegistryService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/4/17 15:18
 * @Version: 0.0.1
 */
@Slf4j
public class Cluster {

    @Value("${server.port}")
    private String port;

    private String host;

    private Server MYSELF;

    @Getter
    private List<Server> servers;


    private ClotRegistryConfigProperties clotRegistryConfigProperties;

    public Cluster(ClotRegistryConfigProperties clotRegistryConfigProperties) {
        this.clotRegistryConfigProperties = clotRegistryConfigProperties;
    }

    public void init(){
        try {
            host = new InetUtils(new InetUtilsProperties()).findFirstNonLoopbackHostInfo().getIpAddress();
            log.info(" ===> findFirstNonLoopbackHostInfo :{}", host);
        } catch (Exception e){
            log.error(" ===> findFirstNonLoopbackHostInfo error");
            host = "127.0.0.1";
        }
        MYSELF = new Server("http://" + host + ":" + port, true, false, -1);
        log.info(" ===> MYSELF:{}", MYSELF);

        initServers();

        new ServerHealth(this).checkServerHealth();
    }

    private void initServers() {
        List<Server> servers = new ArrayList<>();
        for (String url : clotRegistryConfigProperties.getServerList()) {
            Server server = new Server();

            if (url.contains("localhost")){
                url = url.replace("localhost", host);
            } else if(url.contains("127.0.0.1")){
                url = url.replace("127.0.0.1", host);
            }
            if (url.equals(MYSELF.getUrl())){
                // 自己的节点
                servers.add(MYSELF);
            } else {
                // 其他的节点
                server.setUrl(url);
                server.setStatus(false);
                server.setLeader(false);
                server.setVersion(-1L);
                servers.add(server);
            }
        }
        this.servers = servers;
    }

    public Server self() {
        MYSELF.setVersion(ClotRegistryService.VERSION.get());
        return MYSELF;
    }

    public Server leader() {
        return this.servers.stream().filter(Server::isStatus)
                .filter(Server::isLeader).findFirst().orElse(null);
    }

}
